package com.leyou.service;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @Author: taft
 * @Date: 2018-9-27 17:01
 */
@Service
public class UploadService {


    private static final Logger logger = LoggerFactory.getLogger(UploadService.class);

    // 支持的文件类型
    private static final List<String> suffixes = Arrays.asList("image/png", "image/jpeg");

    @Autowired
    private FastFileStorageClient storageClient;


    public String upload(MultipartFile file) {

        //TODO 写IO读取保存file对象到服务器

        try {
            String contentType = file.getContentType();

            //1，校验文件的类型
            if (!suffixes.contains(contentType)){
                logger.error("上传失败，不支持的文件类型{}",contentType);
                return null;
            }

            //2，校验文件的内容,使用图片的读取对象去读，如果能读取，说明是图片
            BufferedImage image = ImageIO.read(file.getInputStream());
            if (image == null) {
                logger.error("上传失败，文件内容有误");
                return null;
            }

            // 2、保存图片
            // 2.1、生成保存目录
            // 2.1、获取文件后缀名 cl.jpg
            String extension = StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
            // 2.2、上传
            StorePath storePath = this.storageClient.uploadFile(
                    file.getInputStream(), file.getSize(), extension, null);
            // 2.3、返回完整路径
            return "http://image.leyou.com/" + storePath.getFullPath();

        } catch (IOException e) {
            e.printStackTrace();
        }


        return "http://img10.360buyimg.com/popshop/jfs/t2119/133/2264148064/4303/b8ab3755/56b2f385N8e4eb051.jpg";
    }
}
